package com.huluobo.lc.kotlinim1812a.contract.login

import android.util.Log
import com.huluobo.lc.kotlinim1812a.adapter.EMCallbackAdapter
import com.huluobo.lc.kotlinim1812a.extenttion.isValidPassword
import com.huluobo.lc.kotlinim1812a.extenttion.isValidUserName
import com.hyphenate.chat.EMClient

/**
 * @author Lc,
 * @description:1.验证用户名合法,2.验证密码是否合法,3.开始登录,触发进度条4登录到环信返回成功或者失败
 * @date :2021/6/21 13:42
 */
class LoginPresenter(private val view: LoginContract.View) : LoginContract.Presenter {
    override fun login(userName: String, password: String) {
        //1.验证用户名合法
        if (userName.isValidUserName()) {
            //2.验证密码是否合法
            if (password.isValidPassword()) {
                //3.开始登录触发进度条
                view.onStartLogin()
                loginEaseMob(userName, password)//登录到环信
            } else view.onPasswordError()
        } else view.onUserNameError()
    }

    //相当于M层
    private fun loginEaseMob(userName: String, password: String) {
        EMClient.getInstance().login(userName, password, object : EMCallbackAdapter() {
            override fun onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups()
                EMClient.getInstance().chatManager().loadAllConversations()
                runOnUIThread { view.onLoggedInSuccess() }
            }

            override fun onError(code: Int, error: String?) {
                Log.i("TagA", "onError:$code,error:$error")
                runOnUIThread { view.onLoggedInFailed() }
            }
        })
    }
}